import { uni, PLATFORM } from "./platform"

function biggerThan(v1: string, v2: string) {
    let v1Array: any[] = v1.split('.')
    let v2Array: any[] = v2.split('.')
    let update = false
    for (let index = 0; index < v2Array.length; index++) {
        let diff = v1Array[index] - v2Array[index]
        if (diff !== 0) {
            update = diff > 0
            break
        }
    }
    return update
}
function dataUrlToBase64(str: string) {
    let array = str.split(',')
    return array[array.length - 1]
}
export function base64ToPath(base64: string) {
    return new Promise(function (resolve, reject) {
        const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
        if (/^mp/.test(PLATFORM)) {
            const fs = uni.getFileSystemManager()
            //自定义文件名
            if (!format) {
                console.error('ERROR_BASE64SRC_PARSE')
                reject(new Error('ERROR_BASE64SRC_PARSE'))
            }
            const time = new Date().getTime();
            const filePath = `${uni.env.USER_DATA_PATH}/${time}.${format}`
            fs.writeFile({
                filePath,
                data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
                encoding: 'base64',
                success() {
                    resolve(filePath)
                },
                fail(err) {
                    console.error('获取base64图片失败', JSON.stringify(err))
                    reject(err)
                }
            })
            return
        }
        if (PLATFORM == 'plus') {
            let extName: RegExpMatchArray | null | string = base64.split(',')[0].match(/data\:\S+\/(\S+);/)
            if (extName) {
                extName = extName[1]
            } else {
                reject(new Error('base64 error'))
            }
            let fileName = Date.now() + '.' + extName

            let basePath = '_doc'
            let dirPath = 'uniapp_temp'
            let filePath = basePath + '/' + dirPath + '/' + fileName
            if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {
                plus.io.resolveLocalFileSystemURL(basePath, function (entry) {
                    entry.getDirectory(dirPath, {
                        create: true,
                        exclusive: false,
                    }, function (entry) {
                        entry.getFile(fileName, {
                            create: true,
                            exclusive: false,
                        }, function (entry) {
                            entry.createWriter(function (writer) {
                                writer.onwrite = function () {
                                    resolve(filePath)
                                }
                                writer.onerror = reject
                                writer.seek(0)
                                writer.writeAsBinary(dataUrlToBase64(base64))
                            }, reject)
                        }, reject)
                    }, reject)
                }, reject)
                return
            }
            let bitmap = new plus.nativeObj.Bitmap(fileName)
            bitmap.loadBase64Data(base64, function () {
                bitmap.save(filePath, {}, function () {
                    bitmap.clear()
                    resolve(filePath)
                }, function (error) {
                    bitmap.clear()
                    reject(error)
                })
            }, function (error) {
                bitmap.clear()
                reject(error)
            })
            return
        }
        reject(new Error('not support'))
    })
}

export function getImageInfo(path: string): Promise<string | undefined> {
    return new Promise(async (resolve, reject) => {
        let src = path
        if ((PLATFORM == 'plus' || /^mp/.test(PLATFORM)) && /data:image\/(\w+);base64,(.*)/.test(path)) {
            try {
                src = await base64ToPath(path)
            } catch (error) {
                console.log(error)
            }
        }
        uni.getImageInfo({
            src,
            success: res => resolve(res),
            fail: err => reject(err)
        })
    }
    );
}

export function getAccessSync(path: string): boolean {
    try {
        if (typeof uni.getFileSystemManager == 'function' && !/implemented/.test(uni.getFileSystemManager.toString())) {
            uni.getFileSystemManager().accessSync(`${path}`)
        }
        return true
    } catch (e) {
        return false
    }
}